import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common/base/base_controller.dart';
import 'package:wan_android_flutter/common/network/model/favorites_model.dart';
import 'package:wan_android_flutter/common/utils/mmkv/mmkv_key.dart';
import 'package:wan_android_flutter/common/utils/mmkv/mmkv_util.dart';

import '../../common/network/http_util.dart';
import '../../common/network/json_parse.dart';
import 'favorite_state.dart';

class FavoriteLogic extends BaseController {
  final FavoriteState state = FavoriteState();

  EasyRefreshController controller = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  void onInit() {
    super.onInit();
    state.cookie = MMKVUtil.instance.getString(MMKVKey.cookie);
  }

  @override
  Future<void> onLoadData() async {
    super.onLoadData();
    loadFavorites();
  }

  Future<void> loadFavorites() async {
    final response = await httpUtil.get("/lg/collect/list/${state.pageIndex}/json",
        options: Options(headers: {"cookie": state.cookie}));
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final favoritesModel = JsonParse.fromJsonMap<FavoritesModel>(response.data);
      if (favoritesModel?.data?.datas?.isNotEmpty == true) {
        if (state.pageIndex == 0) {
          state.favoriteList.assignAll(favoritesModel!.data!.datas!);
        } else {
          state.favoriteList.addAll(favoritesModel!.data!.datas!);
        }
        state.favorites.assignAll(state.favoriteList);
        controller.finishRefresh();
        controller.finishLoad();
      }
    }
  }
}
